local sessionDeviceSetKeyPrefix = KEYS[1]..':'
local deviceSessionSetKeyPrefix = KEYS[2]..':'
local screenSocketServerHashKey = KEYS[3]
local sessionKey = KEYS[4]
local HASH_SCREEN_SESSION_PROJECT = KEYS[5]
local SET_SCREEN_PROJECT_SESSION = KEYS[6]

local SET_SCREEN_SESSION_COMPUTER = KEYS[7]..':'
local SET_SCREEN_COMPUTER_SESSION = KEYS[8]..':'
local SET_SCREEN_SESSION_DUID = KEYS[9]..':'
local SET_SCREEN_DUID_SESSION = KEYS[10]..':'
local SET_SCREEN_INSTANCE = KEYS[11]..':'
local userId = KEYS[12]

local disconnect
local disconnectCount
local tmp


--删除用户与项目的绑定
local exist_projectId = redis.call("HGET",HASH_SCREEN_SESSION_PROJECT,sessionKey)
if exist_projectId then
    redis.call("srem",SET_SCREEN_PROJECT_SESSION..":"..exist_projectId,sessionKey)
end
redis.call("HDEL",HASH_SCREEN_SESSION_PROJECT,sessionKey)


--查找当前用户已经绑定的上位机
local exist_computer = redis.call("smembers",SET_SCREEN_SESSION_COMPUTER..sessionKey)
--删除上位机与用户的绑定关联
if next(exist_computer) ~=nil then
    for _, cuid in ipairs(exist_computer) do
        redis.call("srem",SET_SCREEN_COMPUTER_SESSION..cuid,sessionKey)
    end
end
--删除用户与上位机的绑定关联
redis.call("del",SET_SCREEN_SESSION_COMPUTER..sessionKey)



--查找当前用户已经绑定的状态设备
local exist_duid = redis.call("smembers",SET_SCREEN_SESSION_DUID..sessionKey)
--删除状态设备与用户的绑定关联
if next(exist_duid) ~=nil then
    for _, duid in ipairs(exist_duid) do
        redis.call("srem",SET_SCREEN_DUID_SESSION..duid,sessionKey)
    end
end
--删除用户与状态设备的绑定关联
redis.call("del",SET_SCREEN_SESSION_DUID..sessionKey)


--删除大屏用户与服务器的绑定关联
redis.call("HDEL",screenSocketServerHashKey,sessionKey)

--查找当前用户已经绑定的设备
local setkey = sessionDeviceSetKeyPrefix..sessionKey
local exist = redis.call("smembers",setkey)

--删除设备与用户的绑定关联
if next(exist) ~=nil then
    for _, device in ipairs(exist) do
        redis.call("srem",deviceSessionSetKeyPrefix..device,sessionKey)
    end

--    -- 检查设备是否还有用户绑定，如果没有绑定，则需要发消息给设备，通知不用再发数据
--    for _, device in ipairs(exist) do
--        disconnectCount = tonumber(redis.call("SCARD",deviceSessionSetKeyPrefix..device))
--        if(disconnectCount <= 0) then
--            tmp = redis.call("get",device)
--            if  tmp then
--                disconnectCount = disconnectCount + 1
--            end
--        end
--        if(disconnectCount <= 0) then
--            if disconnect then
--                disconnect = disconnect..','..device
--            else
--                disconnect = device
--            end
--        end
--    end
end
--删除用户与设备的绑定关联
redis.call("del",setkey)

--删除用户与实例的绑定关联
redis.call("srem",SET_SCREEN_INSTANCE..userId,sessionKey)

if not disconnect then
    disconnect = ''
end
return disconnect